// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package vn.hanelsoft.openwifi.control;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.common.ConstCommon;
import vn.hanelsoft.openwifi.common.UtilsCommon;
import vn.hanelsoft.openwifi.common.network_service.utils.NetworkUtil;
import vn.hanelsoft.openwifi.model.delegate.ServerDelegate;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ClipDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

/*
 * This is a lightweight activity for tests that only require WebView functionality.
 */
@SuppressLint("HandlerLeak")
public class ChromeBrowserActivity extends Activity {
	private String INITIAL_URL = "http://google.com";
	private WebView mWebView;
	private EditText mUrlTextView;
	private ImageView mPrevButton;
	private ImageView mNextButton;
	private TextView mTextDown;

	private LinearLayout mToolbar;
	private ClipDrawable mProgressDrawable;

	private boolean mIsLoading = false;

	private static final long COMPLETED_PROGRESS_TIMEOUT_MS = 200;

	boolean checkDisconnectWifi = true;
	Intent mIntentKillService;
	boolean isClickAds;
	private Runnable mClearProgressRunnable = new Runnable() {
		@Override
		public void run() {
			mProgressDrawable.setLevel(0);
		}
	};

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStop() {
		if (checkDisconnectWifi == false) {
			checkDisconnectWifi = true;
		} else if (isClickAds) {
			isClickAds = false;
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst){
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				}
				else
					ConstCommon.totalSecondService = (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterWait;
				ConstCommon.secondService = 0;
				ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE), String
						.valueOf(ConstCommon.totalSecondService));
			}
		} else {
			//
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst){
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				}
				else
					ConstCommon.totalSecondService += (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterFirst;
				ConstCommon.secondService = 0;
			}
			ServerDelegate.updateTotalTimeShowAd(mhandler, UtilsCommon
					.getStringSetting(getBaseContext(),
							ConstCommon.KEY_WIFI_STORE), String
					.valueOf(ConstCommon.totalSecondService));
			ConstCommon.totalSecondService = 0;
			ConstCommon.isServiceRunning = false;
			UtilsCommon.setStringSetting(getBaseContext(), ConstCommon.KEY_WIFI_STORE, "");
			Log.i("Service1", "Kill");
		}
		super.onStop();
	}

	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				UtilsCommon.killApp(getApplicationContext());
			}
		}
	};

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		checkDisconnectWifi = false;
		// if(ConstCommon.totalSecondService == 0)
		// ConstCommon.totalSecondService = 2-ConstCommon.minuterService;
		// else
		// ConstCommon.totalSecondService += 10-ConstCommon.minuterService;
		// ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
		// .getStringSetting(ChromeBrowserActivity.this,
		// ConstCommon.KEY_WIFI_STORE), String
		// .valueOf(ConstCommon.totalSecondService));
		// ConstCommon.totalSecondService = 0;
		activityFinish();
	}

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_chrome_browser);
		checkDisconnectWifi = true;
		createWebView();
		isClickAds = false;
		ConstCommon.isFirst = true;
		mToolbar = (LinearLayout) findViewById(R.id.toolbar);
		mProgressDrawable = (ClipDrawable) mToolbar.getBackground();

		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.requestFocus();

		initializeUrlField();
		initializeNavigationButtons();

		String startupUrl = getUrlFromIntent(getIntent());
		if (TextUtils.isEmpty(startupUrl)) {
			startupUrl = INITIAL_URL;
		}
		if (NetworkUtil.checkNetWork(getApplicationContext())) {
			mWebView.loadUrl(startupUrl);
		} else {
			Toast.makeText(this, getString(R.string.not_connect_internet),
					Toast.LENGTH_LONG).show();
		}
		mUrlTextView.setText(startupUrl);

		AdView adViewBanner = (AdView) this.findViewById(R.id.app_admob_banner);
		AdRequest request = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
				.addTestDevice("9234EBAE83E894E6271DEBE7B380782E").build();
		adViewBanner.loadAd(request);
		adViewBanner.setAdListener(new AdListener() {

			@Override
			public void onAdOpened() {
				super.onAdOpened();
				isClickAds = true;
				ServerDelegate.updateTotalTimeClickAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE));
			}

			@Override
			public void onAdLoaded() {
				// TODO Auto-generated method stub
				super.onAdLoaded();
				Log.i("Service1", UtilsCommon.getStringSetting(getBaseContext(), ConstCommon.KEY_WIFI_STORE));
				if (!UtilsCommon.getStringSetting(ChromeBrowserActivity.this, ConstCommon.KEY_WIFI_STORE).equals(""))
					ConstCommon.isServiceRunning = true;
			}

		});
		AdView adViewFooter = (AdView) this.findViewById(R.id.app_admob_footer);
		adViewFooter.loadAd(request);
		adViewFooter.setAdListener(new AdListener() {

			@Override
			public void onAdOpened() {
				super.onAdOpened();
				isClickAds = true;
				ServerDelegate.updateTotalTimeClickAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE));
			}

			@Override
			public void onAdLoaded() {
				// TODO Auto-generated method stub
				super.onAdLoaded();
				Log.i("Service1", UtilsCommon.getStringSetting(getBaseContext(), ConstCommon.KEY_WIFI_STORE));
				if (!UtilsCommon.getStringSetting(ChromeBrowserActivity.this, ConstCommon.KEY_WIFI_STORE).equals(""))
					ConstCommon.isServiceRunning = true;
			}

		});

		mThread.start();

		mTextDown.setTypeface(UtilsCommon.getFontCustom(this));
	}

	Thread mThread = new Thread(new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setTextDown();
					}
				});
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	});

	void setTextDown() {
		String strMinuter = "";
		String strSecond = "";
		String strTime = "";
		if (ConstCommon.isServiceRunning) {
			if (ConstCommon.minuterService > 9)
				strMinuter += ConstCommon.minuterService;
			else
				strMinuter += "0" + ConstCommon.minuterService;
			if (ConstCommon.secondService > 9)
				strSecond += ConstCommon.secondService;
			else
				strSecond += "0" + ConstCommon.secondService;
			strTime = strMinuter + ":" + strSecond;
		}

		mTextDown.setText(strTime);
	}

	private void createWebView() {
		try {
			INITIAL_URL = getIntent().getExtras().getString(
					ConstCommon.KEY_LINK_POLICY);
		} catch (Exception e) {
			// TODO: handle exception
		}
		mWebView = (WebView) findViewById(R.id.web_view);
		WebViewClient webViewClient = new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				mIsLoading = true;
				if (mUrlTextView != null) {
					mUrlTextView.setText(url);
				}
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				mIsLoading = false;
			}

			@Override
			public void onReceivedHttpAuthRequest(WebView view,
					final HttpAuthHandler handler, final String host,
					final String realm) {
				String username = null;
				String password = null;

				boolean reuseHttpAuthUsernamePassword = handler
						.useHttpAuthUsernamePassword();

				if (reuseHttpAuthUsernamePassword && view != null) {
					String[] credentials = view.getHttpAuthUsernamePassword(
							host, realm);
					if (credentials != null && credentials.length == 2) {
						username = credentials[0];
						password = credentials[1];
					}
				}

				if (username != null && password != null) {
					handler.proceed(username, password);
				} else {
					// if (!handler.suppressDialog()) {
					// mPageDialogsHandler.showHttpAuthentication(handler,
					// host, realm);
					// } else {
					// handler.cancel();
					// }
				}
			}
		};

		WebChromeClient webChromeClient = new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				mToolbar.removeCallbacks(mClearProgressRunnable);
				mProgressDrawable.setLevel(newProgress * 100);
				if (newProgress == 100)
					mToolbar.postDelayed(mClearProgressRunnable,
							COMPLETED_PROGRESS_TIMEOUT_MS);
			}
		};

		mWebView.setWebViewClient(webViewClient);
		mWebView.setWebChromeClient(webChromeClient);
	}

	private static String getUrlFromIntent(Intent intent) {
		return intent != null ? intent.getDataString() : null;
	}

	private void setKeyboardVisibilityForUrl(boolean visible) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (visible) {
			imm.showSoftInput(mUrlTextView, InputMethodManager.SHOW_IMPLICIT);
		} else {
			imm.hideSoftInputFromWindow(mUrlTextView.getWindowToken(), 0);
		}
	}

	private void initializeUrlField() {
		mUrlTextView = (EditText) findViewById(R.id.url);
		mUrlTextView.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if ((actionId != EditorInfo.IME_ACTION_GO)
						&& (event == null
								|| event.getKeyCode() != KeyEvent.KEYCODE_ENTER || event
								.getKeyCode() != KeyEvent.ACTION_DOWN)) {
					Log.i("TimeDown", "false");
					return false;
				}

				if (NetworkUtil.checkNetWork(getApplicationContext())) {
					mWebView.clearCache(true);
					mWebView.loadUrl(UtilsCommon.formartUrl(mUrlTextView
							.getText().toString()));
				} else {
					Toast.makeText(ChromeBrowserActivity.this,
							getString(R.string.not_connect_internet),
							Toast.LENGTH_LONG).show();
				}
				mUrlTextView.clearFocus();
				setKeyboardVisibilityForUrl(false);
				mWebView.requestFocus();
				Log.i("TimeDown", "true");
				return true;
			}
		});
		mUrlTextView.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				setKeyboardVisibilityForUrl(hasFocus);
				mNextButton.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
				mPrevButton.setVisibility(hasFocus ? View.GONE : View.VISIBLE);
				if (!hasFocus) {
					mUrlTextView.setText(mWebView.getUrl());
				}
			}
		});
		mTextDown = (TextView) findViewById(R.id.chrome_text_time_down);
	}

	private void initializeNavigationButtons() {
		mPrevButton = (ImageView) findViewById(R.id.prev);
		mPrevButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mWebView.canGoBack()) {
					mWebView.goBack();
				}
			}
		});

		mNextButton = (ImageView) findViewById(R.id.next);
		mNextButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mWebView.canGoForward()) {
					mWebView.goForward();
				}
			}
		});
	}

	public WebView getWebView() {
		return mWebView;
	}

	public boolean isLoading() {
		return mIsLoading;
	}

	void activityFinish() {
		finish();
		overridePendingTransition(
				R.drawable.activity_transaction_trans_right_in,
				R.drawable.activity_transaction_trans_right_out);
	}
}
